package com.vast.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vast.entity.ProblemEntity;
import com.vast.mapper.ProblemMapper;
import com.vast.service.ProblemService;
import common.utils.Result;
import common.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;


@Service("problemService")
public class ProblemServiceImpl implements ProblemService {
    @Autowired
    ProblemMapper problemMapper;
    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 添加问题
     * @param problemEntity
     */
    @Override
    public void saveProblemList(ProblemEntity problemEntity) {
        problemMapper.insert(problemEntity);
    }

    /**
     * 查询问题
     * @param problemEntity
     * @return
     */
    @Override
    public Result getProblemList(ProblemEntity problemEntity) {
        //构建查询条件
        Query query = new Query();
        query.with(Sort.by(Sort.Order.desc("clickRate")));

        //分页查询
        long count = mongoTemplate.count(query,ProblemEntity.class);

        int offSet = (problemEntity.getPageNum() - 1) * problemEntity.getPageSize();

        long pages = (count % problemEntity.getPageSize() > 0) ? (count / problemEntity.getPageSize() + 1) : (count / problemEntity.getPageSize());

        HashMap<Object, Object> map = new HashMap<>();
        map.put("totalPage",pages);
        map.put("count",count);

        query.skip(offSet).limit(problemEntity.getPageSize());
        List<ProblemEntity> list = null;
        if(null != problemEntity.getProblemContent() && !"".equals(problemEntity.getProblemContent())){
            list = mongoTemplate.find(query.addCriteria(Criteria.where("problemContent")
                    .regex(problemEntity.getProblemContent())), ProblemEntity.class);
        }else{
            list = mongoTemplate.find(query,ProblemEntity.class);
        }
        map.put("list",list);
        return new Result(StatusCode.OK,"分页查询成功",true,map);
    }
}
